﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyWeb.ServiceBus.Common;
using MyWeb.ServiceBus.Model;
using MyWeb.ServiceBus.Model.Models;
using MyWeb.ServiceBus.Services;
using MyWeb.ServiceBus.Services.Db;

namespace MyWeb.ServiceBus.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SysServerController : ControllerBase
    {
        private ISysServerService _service;
        private Context db;
        public SysServerController(ISysServerService service, Context context)
        {
            _service = service;
            db = context;
        }

        [HttpGet]
        public async Task<IActionResult> Get()
        {
            var org = await _service.QueryAsync(o => 1 == 1);
            return Ok(org);
        }
        [HttpGet]
        public ApiResult GetPage(string key = "",int page = 1, int pageSize = 5,long appId = 0)
        {

            List<SysService> apps = new List<SysService>();
            long count = 0;
            // 执行分页查询

            if (appId <= 0)
            {
                apps = _service.QueryPage(s => s.Code.Contains(key),out count, page, pageSize);
            }
            else
            {
                apps = _service.QueryPage(s=>s.AppId == appId && s.Code.Contains(key), out count, page, pageSize);
            }
            var pageData = new Model.PageModel(page, (int)count, pageSize, apps);

            return ApiResult.SUCCESS(res: pageData);
        }

        [HttpPost]
        public async Task<ApiResult> Add(SysService app)
        {
            app.CreateDate = DateTime.Now;
            app.Id = Snowflake.NextId();
            var com = await _service.AddAsync(app);
            return com >= 1 ? ApiResult.SUCCESS() : ApiResult.FAILED();
        }
        [HttpPut]
        public async Task<ApiResult> Edit(SysService app)
        {
            app.UpdateDate = DateTime.Now;
            var com = await _service.EditAsync(app);
            return com >= 1 ? ApiResult.SUCCESS() : ApiResult.FAILED();
        }
        [HttpDelete]
        public async Task<ApiResult> Remove(long id)
        {
            var s = _service.Query(a => a.Id == id);
            var com = await _service.DeleteAsync(s.First());
            return com >= 1 ? ApiResult.SUCCESS() : ApiResult.FAILED();
        }
        [HttpGet]
        public async Task<ApiResult> GetAppList(long oid = 0)
        {
            var list = ( from s in db.AppSystem
                        where s.OrgId == oid || oid <= 0
                        select new
                        {
                            Id = s.Id,
                            Name = s.CNName,
                            Code = s.Code,
                            Item = ( from a in db.Application where a.AppSystemId == s.Id select a).ToList()
                        } ).ToList();
            return ApiResult.SUCCESS(list);
        }
    }
}
